package num06;

/**
 * 6. Z 字形变换
 * 直观规律解法
 */
class Solution {
    public static void main(String[] args) {
        System.out.println(new Solution().convert("PAYPALISHIRING", 4));
    }

    public String convert(String s, int r) {
        int n = s.length();

        if (n == 1 || r == 1) {
            return s;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < r; i++) {
            if (i == 0 || i == r - 1) {
                int j = i;
                int rowOffset = (r - 1) * 2 - 1;
                while (j < n) {
                    sb.append(s.charAt(j));
                    j += rowOffset + 1;
                }
            } else {
                int j = i;

                int topRow = i;
                int topOffset = topRow * 2 - 1;

                int bottomRow = r - i - 1;
                int bottomOffset = bottomRow * 2 - 1;

                boolean flag = true;

                while (j < n) {
                    sb.append(s.charAt(j));
                    j += flag ? bottomOffset + 1 : topOffset + 1;
                    flag = !flag;
                }
            }
        }
        return sb.toString();
    }
}